/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.filter.phone.password;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.api.security.service.SecurityUserService;
import org.elsfs.cloud.common.security.filter.AbsAuthenticationProvider;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

/**
 * 账号密码登录处理提供者
 *
 * @author zeng
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Slf4j
@RequiredArgsConstructor
public class PhonePasswordAuthenticationProvider extends AbsAuthenticationProvider {
  private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
  private final PasswordEncoder passwordEncoder;
  private final SecurityUserService securityUserService;
  private UserDetailsPasswordService userDetailsPasswordService;

  /**
   * 验证密码
   *
   * @param userDetails 检查的源数据
   * @param authentication 携带的数据
   * @throws AuthenticationException e
   */
  protected void additionalAuthenticationChecks(
      UserDetails userDetails, AbstractAuthenticationToken authentication)
      throws AuthenticationException {
    if (authentication.getCredentials() == null) {
      LOGGER.debug("Failed to authenticate since no credentials provided");
      throw new BadCredentialsException(
          this.messages.getMessage(
              "PhonePasswordAuthenticationProvider.badPhone", "Bad phone number or credentials"));
    } else {
      String presentedPassword = authentication.getCredentials().toString();
      if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        LOGGER.debug("Failed to authenticate since password does not match stored value");
        throw new BadCredentialsException(
            this.messages.getMessage(
                "PhonePasswordAuthenticationProvider.badPhone", "Bad phone number or credentials"));
      }
    }
  }

  protected void doAfterPropertiesSet() {
    Assert.notNull(this.securityUserService, "A UserDetailsService must be set");
  }

  @Override
  protected final UserDetails retrieveUser(
      String username, AbstractAuthenticationToken authentication) throws AuthenticationException {
    try {
      UserDetails loadedUser = this.getSecurityUserService().loadUserByPhone(username);
      if (loadedUser == null) {
        throw new InternalAuthenticationServiceException(
            "UserDetailsService returned null, which is an interface contract violation");
      } else {
        return loadedUser;
      }
    } catch (UsernameNotFoundException | InternalAuthenticationServiceException var4) {
      throw var4;
    } catch (Exception var6) {
      throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
    }
  }

  protected Authentication createSuccessAuthentication(
      Object principal, Authentication authentication, UserDetails user) {
    boolean upgradeEncoding =
        this.userDetailsPasswordService != null
            && this.passwordEncoder.upgradeEncoding(user.getPassword());
    if (upgradeEncoding) {
      String presentedPassword = authentication.getCredentials().toString();
      String newPassword = this.passwordEncoder.encode(presentedPassword);
      user = this.userDetailsPasswordService.updatePassword(user, newPassword);
    }

    return super.createSuccessAuthentication(principal, authentication, user);
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return PhonePasswordAuthenticationToken.class.isAssignableFrom(authentication);
  }

  @Override
  public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) {
    super.setHideUserNotFoundExceptions(false);
  }
}
